package com.example.xmltohtml.service;

import com.example.xmltohtml.model.FundProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.File;

@Slf4j
@Service
public class ThymeleafXmlTransformService {

    /*private final TemplateEngine templateEngine;

    public ThymeleafXmlTransformService(TemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }

    public String transformXmlToHtml(String xmlContent) throws IOException {
        try {
            // 解析XML内容
            Document document = parseXml(xmlContent);
            
            // 将XML数据转换为FundProfile对象
            FundProfile fundProfile = convertXmlToFundProfile(document);
            
            // 创建Thymeleaf上下文
            Context context = new Context();
            context.setVariable("fund", fundProfile);
            
            // 使用模板引擎处理模板
            return templateEngine.process("fund_profile", context);
            
        } catch (ParserConfigurationException | SAXException e) {
            log.error("Error processing XML: ", e);
            throw new IOException("Error processing XML", e);
        }
    }

    private Document parseXml(String xmlContent) throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));
    }

    private FundProfile convertXmlToFundProfile(Document document) {
        FundProfile.FundProfileBuilder builder = FundProfile.builder();
        
        // 获取XML节点并设置到FundProfile对象中
        builder.fundCode(getNodeValue(document, "fundCode"))
               .fundName(getNodeValue(document, "fundName"))
               .fundType(getNodeValue(document, "fundType"))
               .establishmentDate(getNodeValue(document, "establishmentDate"))
               .fundSize(getNodeValue(document, "fundSize"))
               .investmentObjective(getNodeValue(document, "investmentObjective"))
               .riskLevel(getNodeValue(document, "riskLevel"))
               .manager(getNodeValue(document, "manager"))
               .custodian(getNodeValue(document, "custodian"))
               .subscriptionFee(getNodeValue(document, "subscriptionFee"))
               .redemptionFee(getNodeValue(document, "redemptionFee"))
               .managementFee(getNodeValue(document, "managementFee"))
               .custodianFee(getNodeValue(document, "custodianFee"))
               .performance(getNodeValue(document, "performance"));
        
        return builder.build();
    }

    private String getNodeValue(Document document, String tagName) {
        NodeList nodeList = document.getElementsByTagName(tagName);
        if (nodeList.getLength() > 0) {
            Node node = nodeList.item(0);
            return node.getTextContent();
        }
        return "";
    }

    @Configuration
    static class ThymeleafConfig {
        @Bean
        public TemplateEngine templateEngine() {
            SpringTemplateEngine templateEngine = new SpringTemplateEngine();
            ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
            templateResolver.setPrefix("templates/");
            templateResolver.setSuffix(".html");
            templateResolver.setTemplateMode(TemplateMode.HTML);
            templateResolver.setCharacterEncoding("UTF-8");
            templateEngine.setTemplateResolver(templateResolver);
            return templateEngine;
        }
    }

    *//**
     * 测试XML转换的main方法
     *//*
    public static void main(String[] args) {
        try {
            // 创建Spring上下文
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
            context.register(ThymeleafConfig.class);
            context.register(ThymeleafXmlTransformService.class);
            context.refresh();

            // 获取Service实例
            ThymeleafXmlTransformService service = context.getBean(ThymeleafXmlTransformService.class);

            // 读取XML文件
            String xmlContent = new String(Files.readAllBytes(Paths.get("src/main/resources/xml/fund_profile_example.xml")), 
                                         StandardCharsets.UTF_8);
            
            // 执行转换
            String htmlContent = service.transformXmlToHtml(xmlContent);
            
            // 将结果保存到文件
            String outputPath = "output/fund_profile_thymeleaf.html";
            Files.createDirectories(Paths.get("output"));
            Files.write(Paths.get(outputPath), htmlContent.getBytes(StandardCharsets.UTF_8));
            
            System.out.println("转换成功！");
            System.out.println("HTML文件已保存到: " + new File(outputPath).getAbsolutePath());
            
            // 关闭Spring上下文
            context.close();
            
        } catch (Exception e) {
            System.err.println("转换过程中发生错误：");
            e.printStackTrace();
        }
    }*/
} 